package com.butioy.study.jersey.filter;

import cn.hutool.core.util.StrUtil;
import com.butioy.study.jersey.exception.NotLoginException;
import com.butioy.study.jersey.utils.Const;
import java.io.IOException;
import java.util.regex.Pattern;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.Provider;

/**
 * @author yanglq
 * @since 3.0.0
 */
@Provider
public class LoginFilter implements ContainerRequestFilter {

    private static final Pattern EXCLUSION_URL_PATTERN = Pattern.compile("user/login");

    @Override
    public void filter(ContainerRequestContext rc) throws IOException {
        String uri = rc.getUriInfo().getPath();
        if (EXCLUSION_URL_PATTERN.matcher(uri).matches()) {
            return;
        }

        MultivaluedMap<String, String> headers = rc.getHeaders();
        String token = headers.getFirst(Const.TOKEN_KEY);

        if (StrUtil.isBlank(token)) {
            throw new NotLoginException("用户未登录或Token已过期");
        }
    }

}
